<?php
/**
 * 秋水
 * 2018/11/28
 * 后台公共控制类
 */
namespace app\tdmin\controller;

use think\Controller;
use \think\auth\Auth;

class Common extends Controller
{
    /**
     * 构造函数
     * @author 秋水
     * @DateTime 2018-11-28T22:28:38+0800
     */
    public function __construct()
    {
        parent::__construct();
        $this->api_code = config('api_code');
        if(!session('admin_uid')) {
            $this->redirect(url('/tdmin/login/index'));
        }
        $menu = $this->getMenuList(session('admin_uid'));
        $this->assign('menu', $menu);
    }
    
    /**
     * 获取菜单权限列表
     * @author 秋水
     * @DateTime 2018-11-29T15:39:30+0800
     * @param    int                   $uid
     */
    public function getMenuList($uid)
    {
        $map = [];
        $map[] = ['type', 'eq', 0];
        $map[] = ['status', 'eq', 1];
        $map[] = ['show', 'eq', 1];
        if(session('admin_uid') !== config('app.auth.super_admin')){
            $ruleIdsArr = $this->getRuleIdsArr($uid);
            $map[] = ['id', 'in', $ruleIdsArr];
        }
        
        // 权限列表组合为有层级的数组
        $ruleList = \Db::name('AuthRule')->where($map)->order('sort desc')->select();
        $result   = $this->ruleListToTree($ruleList, 0);
        return $result;
    }

    /**
     * 获取用户的权限id
     * @author 秋水
     * @DateTime 2018-11-29T16:24:51+0800
     */
    public function getRuleIdsArr($uid)
    {
        $groupAccess = \Db::name('AuthGroupAccess')->where([['uid', 'eq', $uid]])->select();
        // 用户绑定的角色id
        $ruleIds = '';
        foreach ($groupAccess as $key => $o) {
            $group = \Db::name('AuthGroup')->where([['id', 'eq', $o['group_id']]])->find();
            if ($key > 0) {
                $ruleIds .= ',';
            }
            $ruleIds .= $group['rules'];
        }
        // 用户所有的权限id
        $ruleIdsArr = array_unique(explode(',', $ruleIds));
        return $ruleIdsArr;
    }

    /**
     * 权限数组转换为树结构
     * @author 秋水
     * @DateTime 2018-11-29T15:48:30+0800
     * @param    array                   $ruleList
     * @param    int
     */
    public function ruleListToTree($ruleList, $pid)
    {
        $r = [];
        foreach ($ruleList as $key => $o) {
            if ($o['pid'] == $pid) {
                $item             = $o;
                $item['children'] = $this->ruleListToTree($ruleList, $o['id']);
                $r[]              = $item;
            }
        }
        return $r;
    }

    /**
     * 获取表格分级格式的权限列表
     * @author 秋水
     * @DateTime 2018-11-29T16:51:00+0800
     */
    public function ruleListToTable($ruleList, $pid, $level)
    {
        $r   = [];
        $str = '';
        for ($i = 0; $i < $level; $i++) {
            $str .= '&nbsp;&nbsp;&nbsp;&nbsp;';
        }
        $level++;
        foreach ($ruleList as $key => $o) {
            if ($o['pid'] == $pid) {
                $item          = $o;
                $item['title'] = $str . $o['title'];
                $r[]           = $item;
                $childrenR     = $this->ruleListToTable($ruleList, $o['id'], $level);
                $r             = array_merge($r, $childrenR);
            }
        }
        return $r;
    }


    /**
     * [imgUpload 图片上传]
     * @Author   雨夜
     * @DateTime 2019-01-11
     * @return   [type]     [description]
     */
    public function imgUpload()
    {
        $file = request()->file('file');
        if (true !== $this->validate(['file' => $file], ['file' => 'require|image'])) {
            $this->error('请选择图像文件');
        } else {
            $info = $file->validate(['size' => 1204 * 1204 * 10, 'ext' => 'jpg,png,gif'])->move('Uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                $savename = '/Uploads/' . $info->getSaveName();
                return json(['code' => 0, 'msg' => '上传成功', 'data' => $savename]);
            } else {
                // 上传失败获取错误信息
                $error = $file->getError();
                return json(['code' => 40001, 'msg' => $error]);
            }
        }
    }


    /**
     * [textImgUpload 文本图片上传]
     * @Author   雨夜
     * @DateTime 2019-01-11
     * @return   [type]     [description]
     */
    public function textImgUpload()
    {
        $file = request()->file('file');
        if (true !== $this->validate(['file' => $file], ['file' => 'require|image'])) {
            $this->error('请选择图像文件');
        } else {
            $info = $file->validate(['size' => 1204 * 1204 * 10, 'ext' => 'jpg,png,gif'])->move('Uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                $savename = '/Uploads/' . $info->getSaveName();
                return json(['code' => 0, 'msg' => '上传成功', 'data' => ['src' => $savename]]);
            } else {
                // 上传失败获取错误信息
                $error = $file->getError();
                return json(['code' => 40001, 'msg' => $error]);
            }
        }
    }

    /**
     * @author 雨夜
     * @date 2019年3月19日10:36:36
     * @return \think\response\Json
     */
    public function qiniuToken()
    {
        $auth   = new QnAuth(config('site.qiniu_accessKey'), config('site.qiniu_secretKey'));
        $token = $auth->uploadToken(config('site.qiniu_bucket'));
        return json(['code'=>0,'msg'=>'请求成功','data'=>$token]);
    }
}
